<!doctype html>
<html class="no-js">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="小学必备古诗词">
    <meta name="keywords" content="小学必备古诗词">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>小学必背古诗|舒格尔方格(V2.0)</title>
    <link rel="stylesheet" href="//cdn.bootcdn.net/ajax/libs/amazeui/2.7.2/css/amazeui.min.css">
    <style>
    div.box{font-size:24px;margin:0 auto;/*border:1px red dotted;*/height:80px;line-height:80px;}
    caption{font-size: larger;}
    table.puzzle td{height:80px;}
    td.on{background:#ff0;}
    .success-message{font-size: xx-large; color: chocolate;}
    .success{padding:20px;margin-top: 20px;}
    </style>
</head>
<body>
<div id="app" align="center">
    <div v-if="showSuccess" class="success">
        <img :src="successImg" style="width: 90%; margin: auto 0;" />
        <div>
            <strong class="success-message">胜利！获得 500 金币</strong>
            <p><a @click="displayList()">关闭</a></p>
        </div>
    </div>
    <template v-else>
        <div v-if="showList">
            <table border="1" class="basic-table">
            <caption>小学必背古诗|舒格尔方格(V2.0)</caption>
                <tr v-for="(poetry, rindex) in poetryList" :key="rindex">
                    <td>
                        <a href="javascript:void(0)" @click="displayPoetry(poetry.id - 1)">
                            {{ poetry.id }}. 《{{ poetry.title }}》 {{ poetry.author.join(" ") }} ({{ poetry.content.length }})
                        </a>
                    </td>
                </tr>
            </table>
        </div>
        <div v-else>
            <h1>{{ currentPoetry.title }}</h1>
            <h4>{{ currentPoetry.author.join(" ") }}</h4>
            <p><a href="javascript:void(0)" @click="displayList()">返回</a></p>
            <table border="1" class="basic-table puzzle" style="border:2px green solid">
                <tr v-for="(row, rindex) in currentPuzzle" :key="rindex" class="am-vertical-align">
                    <td height="120" width="120" align="center"
                        v-for="(col, cindex) in row" :key="cindex"
                    >
                        <div class="box" @click="clickBox($event)">
                        {{ col }}
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </template>
</div>

<!--在这里编写你的代码-->
<script src="//cdn.staticfile.org/vue/2.6.10/vue.min.js"></script>
<script src="./gushi.js"></script>
<script>
    /**
     * 按照特定方式将字符串分隔为数组
     * @param str
     * @param split 数组段或者1为按单字分隔
     */
    function splitString (str, split) {
        if(split === 1){
            return str.split("");
        }else {
            let from = 0;
            let arr = [];
            split.forEach(function (idx) {
                arr.push(str.substr(from, idx));
                from += idx;
            });

            return arr;
        }
    }

    function chunkArr(arr, size) {
        var data = [];
        for(var i=0;i<arr.length;i=i+size){
            data.push(arr.slice(i,i+size));
        }
        return data;
    }

    /**
     * 将数组打乱
     */
    function shuffleArr (arr) {
        arr = arr.slice();
        let len = arr.length;
        let temp, random_index;
        while (len !== 0) {
            random_index = Math.round((len - 1) * Math.random());
            temp = arr[random_index];
            arr[random_index] = arr[len - 1];
            arr[len - 1] = temp;
            --len;
        }
        return arr;
    }

    function Poetry(poetry) {
        this.id = poetry.title || null;
        this.title = poetry.title || "";
        this.author = poetry.author || [];
        this.content = poetry.content || "";
        this.sentence = this.content.substr(0, this.content.length - 1).split(/[，。？]/);
        this.puzzles = poetry.puzzles || [{split:1, cols: 5}];
        // console.log(this);
    }

    Poetry.prototype.returnPuzzle = function (split, cols) {
        let arr = [];
        this.sentence.forEach(function(line){
            arr = arr.concat(splitString(line, split))
        });

        return chunkArr(shuffleArr(arr), cols)
    };

    Poetry.prototype.makePuzzle = function(mode) {
        let puzzle = this.puzzles[mode] || this.puzzles[0];
        return this.returnPuzzle(puzzle.split, puzzle.cols);
    };
</script>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            successImg: '',
            showSuccess: false, // 是否成功
            currentTime: 0, // 挑战用时秒

            showList: true,
            poetryList : null,
            currentPoetry: null,  // 当前古诗
            currentPuzzle: null,  // 当前谜题
            currentError: 0,   // 当前错误次数
            clickTds: [], // 点击记录器
        },
        methods: {
            displayList: function(){
                this.showList = true;
                this.showSuccess = false;
            },
            displayPoetry: function(id){
            	this.clickTds = [];
            	this.currentError = 0;
                this.showList = false;
                this.currentPoetry = new Poetry(poetryList[id]);
                this.currentPuzzle = this.currentPoetry.makePuzzle(1);  // 使用模式1，这里可以设置多个模式，如0,1,2...
                                                                        // 未来可以随机显示
            },
			clickBox: function(e){
				var selectedBedDom = e.srcElement; //dom元素
				var parent = selectedBedDom.parentNode;

				if(parent.className === 'on'){
					parent.className = 'off';
					this.clickTds.pop();
				}else{
					parent.className = 'on';
					this.clickTds.push(selectedBedDom.innerHTML.trim());
				}

				// 判断是否相同
				var err = false;
				var c = splitString(this.clickTds.join(''), 1);
				var s = splitString(this.currentPoetry.sentence.join(''), 1);
				for(i in c){
					if(c[i] !== s[i]){
						err = true;
						this.currentError ++;
						break;
					}
				}
				console.log(c);
				console.log(s);
				if(err) {
					alert('错误' +this.currentError+ '次');
					parent.className = 'off';
					this.clickTds.pop();
				} else {
				   if(s.length === c.length) {
                    this.displaySuccess();
				   }
				}
			},
            displaySuccess: function() {
                this.showSuccess = true;
                this.showList = true;
                this.successImg = 'img/win' + Math.round(Math.random() * 10) + '.gif';
            }
        },
        created: function () {
            this.poetryList = poetryList;
            // this.displayPoetry(0);
            // this.displaySuccess();
        },
        watched: {
            showSuccess: function () {
                console.info(this.successImg)
            }
        }
    });
</script>
</body>
</html>
